//
//  PreviewFileHelper.m
//  MISCloud
//
//  Created by goldeney on 13-9-24.
//  Copyright (c) 2013年 goldeneye. All rights reserved.
//

#import "PreviewFileHelper.h"
#import "FilePathHelper.h"
#import "WebGetUserInfoToHttp.h"
#import "GEQLPreviewController.h"

@implementation PreviewFileHelper
@synthesize mbProgressHUD = _mbProgressHUD;
@synthesize wjPath = _wjPath;

-(NSData*)getPostData
{
    //传递用户信息
    //传递用户信息
    NSMutableString *body = [[NSMutableString alloc] initWithCapacity:0];
    NSString *sessionValue = [WebGetUserInfoToHttp getUserInfoToJSON];
    [body appendFormat:@"session=%@&",sessionValue];
    
    //删除多余的“&”字符
    if(body.length>0) [body deleteCharactersInRange:NSMakeRange(body.length - 1, 1)];
    return [body dataUsingEncoding:NSUTF8StringEncoding];
}

//字典转Json
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (void)startPreviewInteriorFile:(NSString*)filePath fileName:(NSString*)fileName
{
    //创建提示框
    MainAppDelegate *applation = [[UIApplication sharedApplication] delegate];
    [self showMBProgressHUD:applation.window labelText:@"正在打开文件"];
    
    //如果不存在则创建缓存存储目录
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:[FilePathHelper getCachePhotosFolderPath]])
    {
        [fileManager createDirectoryAtPath:[FilePathHelper getCachePhotosFolderPath] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //文件名称设置
    NSMutableString *nowFileName = [[NSMutableString alloc] init];
    if (!fileName) {
        NSArray *urlCom = [[NSArray alloc]initWithArray:[filePath pathComponents]];
        [nowFileName appendString:[urlCom lastObject]];
    } else if([[fileName pathExtension] isEqualToString:@""]){
        [nowFileName appendString:fileName];
        [nowFileName appendString:@"."];
        [nowFileName appendString:[filePath pathExtension]];
    } else {
        [nowFileName appendString:fileName];
    }
    
    //获取保存地址
    NSString *savePath = [[FilePathHelper getCachePhotosFolderPath] stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"%@",nowFileName]];
    _wjPath = savePath;
    
    //创建网络连接
    ASIHTTPRequest *_request=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:filePath]];
    [_request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [_request setRequestMethod:@"POST"];
    [_request addRequestHeader:@"Accept-Language" value:@"zh-CN"];
    [_request addRequestHeader:@"Charset" value:@"UTF-8"];
    [_request addRequestHeader:@"Connection" value:@"Keep-Alive"];
    
    NSMutableData *postData = [NSMutableData dataWithData:[self getPostData]];
    [_request setPostBody:postData];
    
    _request.delegate = self;
    [_request setDownloadDestinationPath:savePath];
    [_request setTimeOutSeconds:20.0f];
    [_request startAsynchronous];
}


- (void)startPreviewExternalFile:(NSString*)filePath fileName:(NSString*)fileName
{
    //创建提示框
    MainAppDelegate *applation = [[UIApplication sharedApplication] delegate];
    [self showMBProgressHUD:applation.window labelText:@"正在打开文件"];
    
    //如果不存在则创建缓存存储目录
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:[FilePathHelper getCachePhotosFolderPath]])
    {
        [fileManager createDirectoryAtPath:[FilePathHelper getCachePhotosFolderPath] withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //文件名称设置
    NSMutableString *nowFileName = [[NSMutableString alloc] init];
    if (!fileName) {
        NSArray *urlCom = [[NSArray alloc]initWithArray:[filePath pathComponents]];
        [nowFileName appendString:[urlCom lastObject]];
    } else if([[fileName pathExtension] isEqualToString:@""]){
        [nowFileName appendString:fileName];
        [nowFileName appendString:@"."];
        [nowFileName appendString:[filePath pathExtension]];
    } else {
        [nowFileName appendString:fileName];
    }
    
    //获取保存地址
    NSString *savePath = [[FilePathHelper getCachePhotosFolderPath] stringByAppendingPathComponent:
                          [NSString stringWithFormat:@"%@",nowFileName]];
    _wjPath = savePath;
    
    //创建网络连接
    ASIHTTPRequest *_request=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:filePath]];
    [_request setDefaultResponseEncoding:NSUTF8StringEncoding];
    [_request addRequestHeader:@"Accept-Language" value:@"zh-CN"];
    [_request addRequestHeader:@"Charset" value:@"UTF-8"];
    [_request addRequestHeader:@"Connection" value:@"Keep-Alive"];
    
    _request.delegate = self;
    [_request setDownloadDestinationPath:savePath];
    [_request setTimeOutSeconds:20.0f];
    [_request startAsynchronous];
}


#pragma mark -
#pragma mark ASIHTTPRequestDelegate

-(void)requestStarted:(ASIHTTPRequest *)request
{
    NSLog(@"开始了!");
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    int statusCode = [request responseStatusCode];
    NSError *error=[request error];
    
    //如果发生错误，就返回空
    if (!error && statusCode == 404) {
        NSLog(@"无法在服务器找到文件：%d错误",statusCode);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"文件不存在,无法预览该文件！"
                                                     delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    } else if (!error && statusCode == 500) {
        NSLog(@"服务器发生异常：%d错误",statusCode);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"服务器发生异常，无法预览该文件！"
                                                     delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    } else if (!error && statusCode == 403) {
        NSLog(@"服务器拒绝访问：%d错误",statusCode);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您没有权限预览该文件！"
                                                     delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        
    } else if (!error && statusCode==200) {
        //打开文件
        MainAppDelegate *applation = [[UIApplication sharedApplication] delegate];
        GEQLPreviewController *viewController = [[GEQLPreviewController alloc] initWithPathString:_wjPath];
        viewController.delegate = self;
        [applation.navigationController presentViewController:viewController animated:YES completion:nil];
        
    } else {
        NSLog(@"未知错误：%d错误",statusCode);
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"未知错误，无法预览该文件！"
                                                     delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    
    //隐藏提示框
    [self hideMBProgressHUD];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error=[request error];
    NSLog(@"ASIHttpRequest出错了!%@",error);
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"没有连接网络或网络环境差，无法预览该文件！"
                                                 delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
    
    //隐藏提示框
    [self hideMBProgressHUD];
}


#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //失败过后删除文件
    [self previewControllerDidDismiss:nil];
}

#pragma mark -
#pragma mark QLPreviewControllerDelegate
/*!
 * @abstract Invoked before the preview controller is closed.
 */
- (void)previewControllerWillDismiss:(QLPreviewController *)controller
{
    //隐藏标题栏
    [[UIApplication sharedApplication] setStatusBarHidden:NO];
    
    //删除文件
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSError *error;
    [fileManager removeItemAtPath:_wjPath error:&error];
    if(error){
        NSLog(@"删除预览文件出错:%@",error);
    }
}

- (void)previewControllerDidDismiss:(QLPreviewController *)controller
{
    //删除所有文件
    BOOL result = [[NSFileManager defaultManager] removeItemAtPath:[FilePathHelper getCachePhotosFolderPath] error:nil];
    if (!result) NSLog(@"删除所有预览文件出错");
}


#pragma mark -
#pragma mark MBProgressHUD

- (void)showMBProgressHUD:(UIView*)view labelText:(NSString*)labelText {
    if (!_mbProgressHUD) {
        _mbProgressHUD = [[MBProgressHUD alloc] initWithView:view];
        _mbProgressHUD.mode = MBProgressHUDModeDeterminate;
        [view addSubview:_mbProgressHUD];
        
        //如果设置此属性则当前的view置于后台
        _mbProgressHUD.dimBackground = YES;
        if (labelText) {
            _mbProgressHUD.labelText = labelText;
        } else {
            _mbProgressHUD.labelText = @"请稍等";
        }
    }
    
    //显示进度条
    [_mbProgressHUD showAnimated:YES whileExecutingBlock:^{
        float progress = 0.0f;
        while (true) {
            progress += 0.001f;
            _mbProgressHUD.progress = progress;
            usleep(10000);
            if (progress>=1.0f) progress = 0.0f;
        }
    } completionBlock:^{}];
}

- (void)hideMBProgressHUD
{
    if (_mbProgressHUD){
        //[_mbProgressHUD hide:YES];
        [_mbProgressHUD removeFromSuperview];
        _mbProgressHUD = nil;
    }
}


@end
